Skip to content

feat(pm-stack): decision-set event pipeline — Turso sync + Cloudflare Worker/D1/DO (#9335) - #9341

Merged
dezren39 merged 2 commits into
mainfrom
decision-events/9335-trackb
Nov 13, 2026
Merged

dezren39 merged 2 commits into
mainfrom
decision-events/9335-trackb

Conversation

@dezren39

@dezren39 dezren39 commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

What

Track B of Decision Sets v2 (#9335): the external event pipeline for decision-set activity events {eventId, setId, questionRef, type, payload, ts}.

Aggregator side (pm-stack/aggregator)

Worker (pm-stack/decision-events-worker)

  • POST /events (alias /webhook): constant-time shared-secret auth, batch validation (one bad event never poisons a batch), D1 store, then per-set Durable Object fan-out of only the newly inserted events.
  • DecisionSetEvents Durable Object, keyed by idFromName(setId): per-set fan-out state (count, last event) + hibernatable WebSocket subscribers (GET /sets/<id>/stream).
  • GET /sets/<id>/events, GET /sets/<id>/state read-backs (authenticated); GET /health public; fails closed (503) with no secret configured.
  • test/events.test.ts — 7 contract tests; tsc --noEmit clean.

Live state (already deployed — this PR is the source of record)

  • Turso: decision_set_events + indexes created in fleet-platform; verified by independent pipeline read-back.
  • D1: database decision-events (68ade85e-6835-46a8-af6a-a9f2f2d966ae) created, schema.sql applied remotely.
  • Worker: deployed — https://decision-events.developing-today.workers.dev (version 9e5607c8-b26d-47d3-b671-d1465e114253), WEBHOOK_SECRET set from the BWS-vaulted value by name.
  • Secret: newly minted, vaulted in Bitwarden as cloudflare.decision-events.webhook-secret; value never in repo/logs.
  • Smoke (end-to-end, real sync script on the laptop): 3 events for set smoke-9335 → Turso inserted=1×3, Worker inserted=1×3; re-run with fresh state → attempted=3, inserted=0 on both legs (sink-level idempotence); Worker /state shows the DO at fannedOut=3, D1=3; unauthenticated GET/POST → 401.

Verification

  • Aggregator: bun test test/decision-events.test.ts 11/11; neighboring decisions + events suites still green (79/79 across the three files). Typecheck: 20 errors = exact origin/main baseline, 0 in new files.
  • Worker: bun test 7/7, tsc --noEmit clean.
  • A live-response quirk found during the smoke is fixed in this PR: libSQL counts inserts under affected_row_count (not rows_affected) — the counter and the test fake now match the real envelope.

Not in this PR

Track A's local event-log producer (the aggregator-side appends to the outbox) is the parallel leg; this sync consumes whatever JSONL outbox carries the wire shape (--file/--outbox-dir overridable). No timer/cron wiring yet — the sync is safe to run on any cadence once Track A's outbox path is final.

Refs #9335


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

… Worker/D1/DO (#9335)

Track B of Decision Sets v2. Aggregator: src/decision-events.ts (wire shape {eventId,setId,questionRef,type,payload,ts}, JSONL outbox reader, libSQL pipeline client, per-leg sync state) + scripts/sync-decision-events.ts (strict #3352 arg contract; tokens by BWS name turso.fleet-platform-rw-token / cloudflare.decision-events.webhook-secret; INSERT OR IGNORE idempotent on eventId; legs fail independently). Worker: pm-stack/decision-events-worker — POST /events authenticated webhook -> D1 (decision-events DB) + Durable Object per setId (fan-out state + WebSocket stream), GET read-backs, fail-closed auth. Deployed and smoke-verified live; see issue #9335 outcome comment.
@dezren39
dezren39 requested a review from a team as a code owner November 13, 2026 05:30
@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 44 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5c44eefb-7eb2-491b-bfe0-5218e2973365
Commits

Reviewing files that changed from the base of the PR and between c19737b and 66940fb.

Files ignored due to path filters: 1

  • pm-stack/decision-events-worker/bun.lock is excluded by !**/*.lock
Files selected for processing: 11

  • pm-stack/aggregator/scripts/sync-decision-events.ts
  • pm-stack/aggregator/src/decision-events-sync.ts
  • pm-stack/aggregator/test/decision-events.test.ts
  • pm-stack/decision-events-worker/README.md
  • pm-stack/decision-events-worker/package.json
  • pm-stack/decision-events-worker/schema.sql
  • pm-stack/decision-events-worker/src/events.ts
  • pm-stack/decision-events-worker/src/index.ts
  • pm-stack/decision-events-worker/test/events.test.ts
  • pm-stack/decision-events-worker/tsconfig.json
  • pm-stack/decision-events-worker/wrangler.toml
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T05:43:47.002015Z 66940fb New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 81461b36d3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +164 to +170
const changes = r.meta?.changes ?? 0;
inserted += changes;
if (changes > 0) insertedEvents.push(events[i] as DecisionSetEvent);
});

const fanout: Record<string, unknown> = {};
for (const [setId, setEvents] of groupBySet(insertedEvents)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve pending fan-out across D1 deduplication

If the Durable Object ingest fails after the D1 batch commits, these events can never reach the object on retry: their next inserts report zero changes, so insertedEvents excludes them permanently. A non-OK ingest response is also converted into an HTTP 200 webhook response, causing the sync client to acknowledge the events despite the failed fan-out. Persist pending fan-out separately and retry it, with event-ID deduplication at the Durable Object, so transient failures do not permanently lose subscriber notifications and coordination state.

Useful? React with 👍 / 👎.

Comment on lines +308 to +310
const out = (await res.json().catch(() => null)) as { inserted?: unknown } | null;
if (!out || typeof out.inserted !== "number") throw new Error("webhook failed: malformed response");
inserted += out.inserted;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check webhook acceptance before acknowledging the batch

The Worker returns HTTP 200 even when individual events fail validation, but this client checks only inserted and then syncDecisionEvents marks every pending event acknowledged. This occurs with the current implementations: an outbox event with ts: "2026-11-12" passes the aggregator's isIsoDate validation but is rejected by the Worker's timestamp validator, which requires T. The event is consequently never stored in D1 and never retried. Check the response's acceptance count and per-event errors before advancing acknowledgment state, and align the two validators.

Useful? React with 👍 / 👎.

Comment on lines +192 to +195
const after = url.searchParams.get("after");
const query = after
? "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? AND ts > ? ORDER BY ts, event_id LIMIT ?"
: "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? ORDER BY ts, event_id LIMIT ?";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the event ID in the read-back pagination cursor

When a page ends within a group of events sharing the same timestamp, requesting the next page with after equal to the last returned timestamp skips all remaining events in that group. For example, three events with identical ts values and limit=2 make the third event unreachable through pagination. The ordering already uses (ts, event_id); expose and apply that same composite cursor so bounded read-back does not omit events.

Useful? React with 👍 / 👎.

Comment on lines +100 to +104
if (process.env.DECISION_EVENTS_SYNC === "0") {
console.log("sync-decision-events: disabled by DECISION_EVENTS_SYNC=0");
return 0;
}
const opts = parseArgs();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Parse arguments before returning for the kill switch

With DECISION_EVENTS_SYNC=0, the script returns success before validating arguments, so an invocation such as --targte webhook silently succeeds instead of reporting a usage error. This violates the operator-script contract in AGENTS.md, which requires every unaccounted-for argument to produce a non-zero usage error. Move parseArgs() ahead of the kill-switch return so disabled invocations still validate their command line.

AGENTS.md reference: AGENTS.md:L47-L50

Useful? React with 👍 / 👎.

const opts = parseArgs();
const files = opts.files.length > 0 ? [...opts.files] : [defaultDecisionEventsOutboxFile()];
if (opts.outboxDir) {
const entries = await readdir(opts.outboxDir).catch(() => [] as string[]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report failures to read the explicitly requested outbox directory

If the directory supplied through --outbox-dir is unreadable, missing, or actually a regular file, this catch converts the read failure into an empty directory without any diagnostic. The script then continues with the default outbox and can exit successfully with zero pending events while leaving the requested source completely unsynchronized. Propagate directory-read failures or report them and return a non-zero exit status so operators can distinguish a broken source from an empty outbox.

Useful? React with 👍 / 👎.

…trackb

# Conflicts:
#	pm-stack/aggregator/src/decision-events.ts
@dezren39
dezren39 merged commit aad1d36 into main Nov 13, 2026
7 checks passed
@dezren39
dezren39 deleted the decision-events/9335-trackb branch November 13, 2026 05:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant